package thread;

/**
 * @author liweimin
 * @date 2021/1/25 16:01
 * @description 实现Runnable接口，实现多窗口卖票。
 * @since
 */
public class RunnableDemo {
    public static void main(String[] args) {
//        Window1 window1 = new Window1();
//
//        Thread thread1 = new Thread(window1);
//        thread1.setName("窗口1");
//
//        Thread thread2 = new Thread(window1);
//        thread2.setName("窗口1");
//
//        Thread thread3 = new Thread(window1);
//        thread3.setName("窗口1");
//
//        thread1.start();
//        thread2.start();
//        thread3.start();
        WindowDemo1 windowDemo = new WindowDemo1();
//        WindowDemo windowDemo = new WindowDemo();
        Thread thread1 = new Thread(windowDemo);
        thread1.setName("卖票窗口1");

        Thread thread2 = new Thread(windowDemo);
        thread2.setName("卖票窗口2");

        Thread thread3 = new Thread(windowDemo);
        thread3.setName("卖票窗口3");

        thread1.start();

        thread2.start();

        thread3.start();


    }
}

class Window1 implements Runnable {
    /**
     * 三个线程共享同一个window1
     * todo 线程安全
     */
    private int ticket = 100;

    @Override
    public void run() {
        while (ticket > 0) {
            System.out.println(Thread.currentThread().getName() + ": 卖票，票号为： " + ticket);
            ticket--;
        }
    }
}

class WindowDemo implements Runnable {
    /**
     * 三个线程共享同一个window1
     * todo 线程安全
     */
    private int ticket = 100;

    @Override
    public void run() {
        //多个线程必须共用一把锁
        synchronized (this) {
//        synchronized (WindowDemo.class) {
            while (ticket > 0) {
                System.out.println(Thread.currentThread().getName() + ": 卖票，票号为： " + ticket);
                ticket--;
            }
        }
    }
}

class WindowDemo1 implements Runnable {
    /**
     * 使用同步方法
     */
    private int ticket = 100;

    @Override
    public synchronized void run() {
        //多个线程必须共用一把锁
        while (ticket > 0) {
            System.out.println(Thread.currentThread().getName() + ": 卖票，票号为： " + ticket);
            ticket--;
        }
    }
}